package com.burgeon.backend.SHOP.service.Impl;

import com.burgeon.backend.SHOP.entity.*;
import com.burgeon.backend.SHOP.mappers.FavoritesMapper;
import com.burgeon.backend.SHOP.mappers.GoodsMapper;
import com.burgeon.backend.SHOP.rest.FindStorage;
import com.burgeon.backend.SHOP.service.AppActivityService;
import com.burgeon.backend.SHOP.service.GoodsService;
import com.burgeon.backend.SHOP.service.ex.ErrorDataExceptionApp;
import com.burgeon.backend.SHOP.service.util.MathUtil;
import com.burgeon.backend.SHOPBACKEND.rest.QuerryFAStorageYC;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {
    private final static Log logger = LogFactory.getLog(GoodsService.class);

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private FavoritesMapper favoritesMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private AppActivityService AppActivityService;

    //0库存下架
    @Override
    public void TimingOfTheShelves() {
        Thread thread = new Thread(() -> {
            //获取所有上架商品
            List<Goods> goodsList = goodsMapper.goodsAllByInventory();

            //遍历库存
            FindStorage findStorage = new FindStorage();

            for (Goods goods : goodsList) {
                Info info = GetInfo(goods.getToken());
                try {
                    //无库存返回 false
                    boolean row = findStorage.getData(goods.getCode(), info.getUrl(), info.getAccount(), info.getPassword());
                    if (!row){
                        //库存为0下架
                        goodsMapper.upGoodsState(goods.getId(),"N");
                        logger.error("下架的商品:"+goods.getId());
                    }
                } catch (Exception e) {
                    System.err.println("自动下架错误");
                    System.err.println(e.getMessage());
                    logger.error(e.getMessage());

                }

            }


        });
        thread.start();

    }

    @Override
    public Goods getGoodsDataByBase(String id, String discount) {
        Goods data = goodsMapper.getGoods(id);
        //计算会员价
        data.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(data.getOriginal()), new BigDecimal(discount), 0)));

        return data;
    }

    @Override
    public List getGoodsBanners(String id) {
        return goodsMapper.findGoodsBanner(id);
    }

    @Override
    public List<Goods> showGoodsByType(Integer start, String type, String token, String discount) {
        List<Goods> data = goodsMapper.goodsByType(start * 10, type, token);
        for (Goods goods : data) {
            //计算会员价
            goods.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(goods.getOriginal()), new BigDecimal(discount), 0)));

        }
        return data;
    }

    @Override
    public List<Goods> getGoodsAll(String token, String discount, Integer start) {
        List<Goods> data = goodsMapper.goodsAll(start * 10, token);
        for (Goods goods : data) {
            //计算会员价
            goods.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(goods.getOriginal()), new BigDecimal(discount), 0)));

        }
        return data;
    }

    @Override
    public List<Goods> getRecommend(String token, String discount) {
        List<Goods> data = goodsMapper.recommendData(token);
        for (Goods goods : data) {
            //计算会员价
            goods.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(goods.getOriginal()), new BigDecimal(discount), 0)));

        }

        return data;
    }

    @Override
    public List<Goods> findGoodsByBrandId(Integer start, String id, String token, String discount) {
        List<Goods> data = goodsMapper.findGoodsByBrandId(start * 10, id, token);
        for (Goods goods : data) {
            //计算会员价
            goods.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(goods.getOriginal()), new BigDecimal(discount), 0)));

        }
        return data;
    }

    @Override
    public List<Brand> showBrand(String token) {
        return goodsMapper.showBrand(token);
    }

    @Override
    public String queryGoodsCode(String code, String color, String size) {
        return null;
    }

    @Override
    public List<Goods> findGoods(Integer start, String name, String token, String discount) throws ErrorDataExceptionApp {

        try {

            List<Goods> data = goodsMapper.findGoods(start * 10, name, token);
            for (Goods goods : data) {
                //计算会员价
                goods.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(goods.getOriginal()), new BigDecimal(discount), 0)));

            }
            return data;
        } catch (Exception e) {
            System.err.println("搜索商品错误");
            e.printStackTrace();
            throw new ErrorDataExceptionApp("出现错误");
        }
    }


    @Override
    public HashMap getGoodsData(String token, String discount) throws ErrorDataExceptionApp {
        try {
            List<Goods> list = goodsMapper.showGoods(token);

            ArrayList price = new ArrayList();
            ArrayList integral = new ArrayList();
            ArrayList newGoods = new ArrayList();
            for (Goods g : list) {
                //计算会员价
                g.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(g.getOriginal()), new BigDecimal(discount), 0)));


                switch (g.getType()) {
                    case "现金":
                        price.add(g);
                        break;
                    case "积分":
                        integral.add(g);
                        break;
                    case "新品":
                        newGoods.add(g);
                }
            }
            HashMap data = new HashMap();

            data.put("price", price.size() > 20 ? price.subList(0, 20) : price);
            data.put("integral", integral.size() > 20 ? integral.subList(0, 20) : integral);
            data.put("newGoods", newGoods.size() > 20 ? newGoods.subList(0, 20) : newGoods);

            return data;
        } catch (Exception e) {

            logger.error(e.getMessage());
            throw new ErrorDataExceptionApp(e.getMessage());
        }
    }

    @Override
    public Goods findGoodsByIdByappOrderConfig(String id, String uid, String discount, String isPlus) {

        try {
            Goods data = goodsMapper.getGoods(id);
            //计算会员价
            if ("Y".equals(data.getIsVipPrice())) {
                data.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(data.getOriginal()), new BigDecimal(discount), 0)));
            }
            //判断plus会员
            if (!"Y".equals(isPlus)) {
                data.setPlusPrice(null);
            }
            System.err.println(data);
            data.setLowPrice(minPrice(data.getPrice(), data.getVipPrice(), data.getPlusPrice()));

            List<GoodsItem> items = goodsMapper.findGoodsItem(id);
            List<GoodsItemImg> goodsItemImgs = goodsMapper.getGoodsItemImg(id);
            ArrayList itemimg = new ArrayList();
            for (GoodsItemImg goodsItemImg : goodsItemImgs) {
                itemimg.add(goodsItemImg.getImg());
            }
            data.setItemImg(itemimg);
            for (GoodsItem goodsItem : items) {
                goodsItem.setGoodsSizes(goodsMapper.GetGoodsSize(goodsItem.getId()));
            }
            data.setGoodsItems(items);
            data.setNum("1");
            List banner = goodsMapper.findGoodsBanner(data.getId());

            if (!"null".equals(uid)) {
                if (null != favoritesMapper.findFavorite(uid, id)) {
                    data.setIsFavorites("Y");
                } else {
                    data.setIsFavorites("N");
                }
            }
            data.setBanner(banner);
            if (null != data.getActivityId()) {
                data.setActivitieitem(AppActivityService.getActvityById(data.getActivityId()));
            }
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return null;
        }
    }

    /**
     * 订单查询用 数量固定为1
     *
     * @param id
     * @return
     */
    @Override
    public Goods findGoodsById(String id, String uid, String discount, String isPlus) {
        try {
            Goods data = goodsMapper.getGoods(id);
            //计算会员价
            if ("Y".equals(data.getIsVipPrice())) {
                data.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(data.getOriginal()), new BigDecimal(discount), 0)));
            }
            //判断plus会员
            if (!"Y".equals(isPlus)) {
                data.setPlusPrice(null);
            }
            data.setPrice(minPrice(data.getPrice(), data.getVipPrice(), data.getPlusPrice()));

            List<GoodsItem> items = goodsMapper.findGoodsItem(id);
            List<GoodsItemImg> goodsItemImgs = goodsMapper.getGoodsItemImg(id);
            ArrayList itemimg = new ArrayList();
            for (GoodsItemImg goodsItemImg : goodsItemImgs) {
                itemimg.add(goodsItemImg.getImg());
            }
            data.setItemImg(itemimg);
            for (GoodsItem goodsItem : items) {
                goodsItem.setGoodsSizes(goodsMapper.GetGoodsSize(goodsItem.getId()));
            }
            data.setGoodsItems(items);
            data.setNum("1");
            List banner = goodsMapper.findGoodsBanner(data.getId());

            if (!"null".equals(uid)) {
                if (null != favoritesMapper.findFavorite(uid, id)) {
                    data.setIsFavorites("Y");
                } else {
                    data.setIsFavorites("N");
                }
            }
            data.setBanner(banner);
            if (null != data.getActivityId()) {
                data.setActivitieitem(AppActivityService.getActvityById(data.getActivityId()));
            }
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return null;
        }
    }

    private String minPrice(String value1, String value2, String value3) {


        int a = Integer.parseInt(value1 == null ? "2147483647" : value1);
        int b = Integer.parseInt(value2 == null ? "2147483647" : value2);
        int c = Integer.parseInt(value3 == null ? "2147483647" : value3);
        int n = a < b ? a : b; //找出a和b最大值。
        int m = n < c ? n : c;//用n和c比较。
        return String.valueOf(m);
    }

    /**
     * 立即购买生成订单用 数量固定为1
     *
     * @param id
     * @return
     */
    @Override
    public Goods findGoodsNumById(String id, String uid, String token, String discount) {
        try {
            System.err.println("查询商品");
            Goods data = goodsMapper.getGoods(id);
            //计算会员价
            data.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(data.getOriginal()), new BigDecimal(discount), 0)));

            /**新建一个新的arraylist，用来存放erp与数据库，对应的*/
//            ArrayList<GoodQtyCan> goodQtyCans = new ArrayList<>();
            System.err.println(data.getCode());
            //从erp根据款号查询颜色尺寸可配量
            Info info = GetInfo(token);

            QuerryFAStorageYC querryYCDisStatus = new QuerryFAStorageYC(info.getUrl(), info.getAccount(), info.getPassword());
            ArrayList<FaStorage> faStorages = querryYCDisStatus.getData(data.getCode());

            List<GoodsItem> items = goodsMapper.findGoodsItem(id);
            List<GoodsItemImg> goodsItemImgs = goodsMapper.getGoodsItemImg(id);
            ArrayList itemimg = new ArrayList();
            for (GoodsItemImg goodsItemImg : goodsItemImgs) {
                itemimg.add(goodsItemImg.getImg());
            }
            data.setItemImg(itemimg);
            for (GoodsItem goodsItem : items) {
                List<GoodsSize> goodsSizes = goodsMapper.GetGoodsSize(goodsItem.getId());
                for (GoodsSize goodsSize : goodsSizes) {
                    goodsSize.setInventory(0);//重置为0
                    /**将erp查询出来的合并，去重*/
                    for (int i = 0; i < faStorages.size() - 1; i++) {
                        for (int j = faStorages.size() - 1; j > i; j--) {
                            /**颜色和尺寸相同并且门店不同的*/
                            if (faStorages.get(j).getValue1Id().equals(faStorages.get(i).getValue1Id())
                                    && !faStorages.get(j).getcStoreId().equals(faStorages.get(i).getcStoreId())
                                    && faStorages.get(j).getValue2Id().equals(faStorages.get(i).getValue2Id())
                            ) {
                                int num = Integer.parseInt(faStorages.get(j).getQtycam()) +
                                        Integer.parseInt(faStorages.get(i).getQtycam());
                                faStorages.get(i).setQtycam(Integer.toString(num));
                                faStorages.remove(j);
                            }
                        }
                    }
                    /**去重后的，遍历并与数据库的对比，再写入新的ArraryList对象*/
                    for (FaStorage faStorage2 : faStorages) {
                        /**颜色和尺寸相同的*/
                        if (
                                faStorage2.getValue1Id().equals(goodsItem.getName())
                                        && faStorage2.getValue2Id().equals(goodsSize.getName())
                        ) {
                            goodsSize.setInventory(Integer.parseInt(faStorage2.getQtycam()));
                            System.err.println(goodsSize);
                        }
                    }
                }
                goodsItem.setGoodsSizes(goodsSizes);
            }
            data.setGoodsItems(items);
            data.setNum("1");
            List banner = goodsMapper.findGoodsBanner(data.getId());

            if (!"null".equals(uid)) {
                if (null != favoritesMapper.findFavorite(uid, id)) {
                    data.setIsFavorites("Y");
                } else {
                    data.setIsFavorites("N");
                }
            }
            data.setBanner(banner);
            if (null != data.getActivityId()) {
                data.setActivitieitem(AppActivityService.getActvityById(data.getActivityId()));
            }
            System.err.println(data);
            return data;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }


    @Override
    public List<Classify> getClassify(String token) {
        try {
            return goodsMapper.getClassify(token);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    @Override
    public List<Goods> getGoodsByClassify(Integer start, String token, String classify, String discount) {
        try {
            List<Goods> goodsList = goodsMapper.showGoodsByClassify(start * 10, classify, token);
            for (Goods goods : goodsList) {
                //计算会员价
                goods.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(goods.getOriginal()), new BigDecimal(discount), 0)));

            }
            return goodsList;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    @Override
    public Goods findGoodsInfoById(String gid) {
        return goodsMapper.findGoodsInfoById(gid);
    }

    private Info GetInfo(String token) {
        return accountMapper.GetTokenData(token);
    }

}
